package com.kitty.game.pet.service;

import com.kitty.game.equip.model.EquipField;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.model.PetBook;
import com.kitty.game.pet.model.PetStone;
import com.kitty.game.role.model.Role;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.attribute.AttrService;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.identity.IdentityType;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.pet.PetController;
import com.kitty.game.petBook.ReqEnableBook;
import com.kitty.game.role.message.ReqGeneralNotify;
import com.kitty.game.team.message.RespMsg;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.game.base.service.BagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class BookService {

	@Autowired
	EquipService equipService;
	@Autowired
	AttrService attrService;
	@Autowired
	PetService petService;
	@Autowired
	MallService mallService;
	@Autowired
	BagService bagService;

	public int getId() {
		return SpringUtils.getIdentityService().getNextId(IdentityType.BOOK);
	}

	/**
	 * 使用天书
	 *
	 * @return
	 */
	public void useBook(Role role, Pet pet, RoleEquip roleEquip) {
		if (roleEquip.isBookUse()) {
			return;
		}
		int flag = 0 ;
		if(roleEquip.getName().contains("·金色")){
			flag = 1;
			roleEquip.setName(roleEquip.getName().replaceAll("·金色",""));
		}
		//检测是否有重复的。
		Map<Integer, PetBook> books = role.getPetBox().getBooks();
		for (Map.Entry<Integer, PetBook> integerPetBookEntry : books.entrySet()) {
			PetBook value = integerPetBookEntry.getValue();
			if(pet.getId() == value.getPetId() && roleEquip.getName().equals(value.getBookName())){
				MessagePusher.pushMessage(role,new RespNotifyMiscEx("该宠物已经有效果相同的天书了！！！！"));
				log.info("该宠物已经有效果相同的天书了！");
				return;
			}
		}

		NutMap itemInfo = getBookInfo(roleEquip);
		short bookLevel = (short) Math.floor(pet.getLevel() * 1.6);
		if (itemInfo.getInt("num") > 1) {
			int aa = equipService.delEquipNum(role, roleEquip, 1);
			if (aa <= 0) {
				return;
			}
			String content = Json.toJson(roleEquip);
			RoleEquip newEquip = Json.fromJson(RoleEquip.class, content);
			FiedValue fiedValue = newEquip.getFields().get((short) 1).getField().get((short) 203);
			if (fiedValue == null) {
				fiedValue = new FiedValue();
				fiedValue.setType((short) 203);
				fiedValue.setVT((byte) 2);
				newEquip.getFields().get((short) 1).getField().put((short) 203, fiedValue);
			}
			fiedValue.setValue((short) 1);
			newEquip.setBookUse(true);
			newEquip.setPosition(-1);
			int id = mallService.getRoleEquipId();
			newEquip.setId(id);
			equipService.add(role, newEquip);

			PetBook book = new PetBook(getId(), pet.getId(), newEquip.getId(), (short) itemInfo.getInt("icon"),
					newEquip.getName(), (short) itemInfo.getInt("lingqi"), bookLevel, false,
					getFightBookIcon(roleEquip.getName()));
			if(flag == 1){
				book.setIsSuper(1);
			}
			role.getPetBox().addBook(book);
		} else {
			PetBook book = new PetBook(getId(), pet.getId(), roleEquip.getId(), (short) itemInfo.getInt("icon"),
					roleEquip.getName(), (short) itemInfo.getInt("lingqi"), bookLevel, false,
					getFightBookIcon(roleEquip.getName()));
			if(flag == 1){
				book.setIsSuper(1);
			}
			role.getPetBox().addBook(book);
			roleEquip.setBookUse(true);
			equipService.setPositionNull(role, (byte) roleEquip.getPosition());
			roleEquip.setPosition(-1);
		}
		petService.loadPet(role, pet);

		role.save();
	}

	/**
	 * 取天书属性
	 */
	private NutMap getBookInfo(RoleEquip roleEquip) {
		NutMap nutMap = new NutMap();
		FiedValue fiedValue = roleEquip.getFields().get((short) 1).getField().get((short) 118);
		if (fiedValue != null) {
			nutMap.setv("lingqi", attrService.getValue(fiedValue.getValue()));
		} else {
			nutMap.setv("lingqi", 0);
		}
		fiedValue = roleEquip.getFields().get((short) 1).getField().get((short) 40);
		if (fiedValue != null) {
			nutMap.setv("icon", attrService.getValue(fiedValue.getValue()));
		} else {
			nutMap.setv("icon", 1);
		}
		fiedValue = roleEquip.getFields().get((short) 1).getField().get((short) 203);
		if (fiedValue != null) {
			nutMap.setv("num", attrService.getValue(fiedValue.getValue()));
		} else {
			nutMap.setv("num", 1);
		}
		return nutMap;
	}

	/**
	 * 取出宠物天书
	 *
	 * @return
	 */
	public PetBook getPetBook(Role role, int petId, String bookName) {
		Map<Integer, PetBook> bookHashMap = role.getPetBox().getPetBooks(petId);
		for (Map.Entry<Integer, PetBook> entry : bookHashMap.entrySet()) {
			if (entry.getValue().getBookName().equals(bookName)) {
				return entry.getValue();
			}
		}
		return null;
	}

	/**
	 * 启用天书
	 *
	 * @param session
	 * @param reqEnableBook
	 */
	public void enableBook(IoSession session, ReqEnableBook reqEnableBook) {
		Role role = SessionUtils.getRoleBySession(session);
		Pet pet = petService.getPetByPos(reqEnableBook.getPetPos(), role);
		if (pet == null) {
			return;
		}
		String bookName = reqEnableBook.getBookName();
		PetBook petbook = getPetBook(role, pet.getId(), bookName);
		if (petbook == null) {
			return;
		}
		petbook.setEnable(reqEnableBook.isEnable());
		role.save();
		petService.loadPet(role, pet);

		if (reqEnableBook.isEnable()) {
			MessagePusher.pushMessage(session, new RespNotifyMiscEx("当前天书技能已停用，进入战斗将不再消耗灵气。"));
		} else {
			MessagePusher.pushMessage(session, new RespNotifyMiscEx("当前天书技能已启用，进入战斗将正常消耗灵气。"));
		}
	}

	/**
	 * 天书名称取战斗Icon
	 */
	public short getFightBookIcon(String bookName) {
		switch (bookName) {
		case "惊雷":
			return 7031;
		case "青木":
			return 7032;
		case "寒冰":
			return 7033;
		case "烈炎":
			return 7034;
		case "碎石":
			return 7035;
		case "降魔斩":
			return 7036;
		case "狂暴":
			return 7037;
		case "魔引":
			return 7038;
		case "怒击":
			return 7039;
		case "破天":
			return 7040;
		case "修罗术":
			return 7041;
		case "反击":
			return 8049;
		case "仙风":
			return 8050;
		case "云体":
			return 8051;
		case "尽忠":
			return 8240;
		}
		return 0;
	}

	/**
	 * 取出天书
	 */
	public void takeOutBook(Role role, ReqGeneralNotify reqGeneralNotify) {
		byte petPos = Byte.parseByte(reqGeneralNotify.getStatus());
		String bookName = reqGeneralNotify.getString();
		Pet pet = petService.getPetByPos(petPos, role);
		if (pet == null) {
			return;
		}
		PetBook petBook = getPetBook(role, pet.getId(), bookName);
		if (petBook == null) {
			return;
		}
		RoleEquip roleEquip = role.getEquipBox().getRoleEquip(petBook.getRoleEquipId());
		FiedValue fiedValue = roleEquip.getFields().get((short) 1).getField().get((short) 1);
		String name = fiedValue.getValue().toString();
		if(name.contains("金色")){
			petBook.setIsSuper(1);
			roleEquip.setName(roleEquip.getName()+"·金色");
		}
		if (roleEquip == null) {
			return;
		}
		short pos = bagService.getPos(role, false);
		if (pos <= 0) {
			MessagePusher.pushMessage(role, new RespMsg("你的包裹已满，请整理后再来吧。"));
			return;
		}

		role.getPetBox().getBooks().remove(petBook.getId());
		petService.loadPet(role, pet);
		roleEquip.setPosition(pos);
		roleEquip.setBookUse(false);
		equipService.add(role, roleEquip);
		roleEquip.addLimitTime(1);

		role.save();

		equipService.refreshRoleEquip(role, roleEquip);
		MessagePusher.pushMessage(role, new RespIconCartoon(roleEquip.getName()));
	}

	/**
	 * 给宠物添加上增益属性
	 */
	public void addPetExtraFields(Pet pet, List<FiedValue> values) {
		int life = 0;
		int def = 0;
		int mag = 0;
		int phy = 0;
		int mana = 0;
		int speed = 0;
		for (FiedValue value : values) {
			if (value.getType() == 7) {//气血
				life += attrService.getValue(value.getValue());
			} else if (value.getType() == 8) {//防御
				def += attrService.getValue(value.getValue());
			} else if (value.getType() == 10) {//法伤
				mag += attrService.getValue(value.getValue());
			} else if (value.getType() == 3) {//物伤
				phy += attrService.getValue(value.getValue());
			} else if (value.getType() == 12) {//法力
				mana += attrService.getValue(value.getValue());
			} else if (value.getType() == 14) {//速度
				speed += attrService.getValue(value.getValue());
			}
		}
		pet.setBookExtraLife(life);
		pet.setBookExtraDefense(def);
		pet.setBookExtraMagPower(mag);
		pet.setBookExtraPhyPower(phy);
		pet.setBookExtraMana(mana);
		pet.setBookExtraSpeed(speed);
	}


	/**
	 * 取宠物天书增益
	 */
	public List<EquipField> getBookExtra(Role role,Pet pet) {
		List<FiedValue> fiedList = new ArrayList<>();
		Map<Integer, PetBook> bookHashMap = role.getPetBox().getPetBooks(pet.getId());
		for (Map.Entry<Integer, PetBook> entry : bookHashMap.entrySet()) {
			PetBook petBook = entry.getValue();
			//获取天书属性
			RoleEquip roleEquip = role.getEquipBox().getRoleEquip(petBook.getRoleEquipId());
			if (roleEquip == null) {
				continue;
			}
			LinkedHashMap<Short, RoleEquipField> fields = roleEquip.getFields();
			for (Map.Entry<Short, FiedValue> shortFiedValueEntry : fields.get((short)1).getField().entrySet()) {
				fiedList.add(shortFiedValueEntry.getValue());
			}
		}
		addPetExtraFields(pet,fiedList);
		return null;
	}
}
